package com.changgou.util;

import java.util.Base64;
import java.util.Date;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

/**
 * jwt工具类
 *
 * @author gaofeng
 * @date 2025年04月30日 22:49
 */
public class JwtUtils {
    /**
     * 默认token过期时间
     */
    private static final Long JWT_TTL = 1000 * 60 * 60L;

    /**
     * 密钥
     */
    private static final String JWT_KEY = "changgou";

    /**
     * 生成token
     * 
     * @param id 唯一标识
     * @param subject 主题
     * @param ttlMillis 过期时间，默认一小时
     * @return token
     */
    public static String createToken(String id, String subject, Long ttlMillis) {
        SignatureAlgorithm algorithm = SignatureAlgorithm.HS256;

        long nowMillis = System.currentTimeMillis();

        Date now = new Date(nowMillis);

        if (ttlMillis == null) {
            ttlMillis = JWT_TTL;
        }

        long expMillis = nowMillis + ttlMillis;
        Date expireDate = new Date(expMillis);
        SecretKey secretKey = getSecretKey();
        return Jwts.builder().setExpiration(expireDate).setId(id).setSubject(subject).setIssuedAt(now)
            .signWith(algorithm, secretKey).setIssuer("admin").compact();
    }

    /**
     * 解析token
     * 
     * @param jwt token
     * @return jwt声明集
     */
    public Claims parseJwt(String jwt) {
        SecretKey secretKey = getSecretKey();
        return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody();
    }

    private static SecretKey getSecretKey() {
        byte[] encode = Base64.getEncoder().encode(JWT_KEY.getBytes());
        return new SecretKeySpec(encode, 0, encode.length, "AES");

    }
}